
package com.cn.qtms.common.controller;

import com.cn.qtms.common.result.ErrorCode;
import com.cn.qtms.common.result.Result;
import com.cn.qtms.common.result.ResultUtil;
import com.cn.qtms.exception.ApplicationException;
import com.cn.qtms.exception.SystemException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.MessageSource;
import org.springframework.context.MessageSourceAware;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Locale;

@Slf4j
@RestController
/**
 * @Name:BaseRestController
 * @Description:
 * @Author: zhangyang
 * @Date: 2019-08-26 23:45
 **/
public abstract class BaseRestController implements MessageSourceAware {

    public static String ERROR_MESSAGE_CODE_PREFIX = "3101";

    protected MessageSource messageSource;

    @SuppressWarnings("rawtypes")
    @ExceptionHandler
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public @ResponseBody
    Result exceptionHandler(HttpServletRequest request, HttpServletResponse response, Exception e) {
        log.error("Error while doing restful request.", e);
        e.printStackTrace();
        return resultError(ErrorCode.EXCEPTION.getCode(), handleException(e).getLocalizedMessage());

    }

     Exception handleException(Exception e) {
        // localize message.
        if (e instanceof ApplicationException) {
            String code = ((ApplicationException) e).getCode();
            String[] params = ((ApplicationException) e).getParams();
            String message = code;
            try {
                message = messageSource.getMessage(code, params, Locale.getDefault());
            } catch (Exception ee) {
                log.warn("No message found with key:" + code);
            }
            String tmpCode = code.toUpperCase();
            if (code != null && (tmpCode.startsWith("AE") || tmpCode.startsWith("AW") || tmpCode.startsWith("AI"))) {
                e = new ApplicationException(ERROR_MESSAGE_CODE_PREFIX + code + ": " + message);
            } else {
                if (!(message.startsWith(ERROR_MESSAGE_CODE_PREFIX))) {
                    e = new ApplicationException(ERROR_MESSAGE_CODE_PREFIX + "XXXX: " + message);
                }
            }

        } else if (e instanceof SystemException) {
            String code = ((SystemException) e).getCode();
            String[] params = ((SystemException) e).getParams();
            String message = code;
            try {
                message = messageSource.getMessage(code, params, Locale.getDefault());
            } catch (Exception ee) {
                log.warn("No message found with key:" + code);
            }
            e = new SystemException(ERROR_MESSAGE_CODE_PREFIX + code + ": " + message);
        }
        return e;

    }

    /**
     * 返回带有错误代码和信息的结果
     *
     * @param errorCode
     * @param errorMessage
     * @return
     */
    @SuppressWarnings("rawtypes")
    protected Result resultError(Integer errorCode, String errorMessage) {
        return ResultUtil.error(errorCode, errorMessage);
    }


    @Override
    public void setMessageSource(MessageSource messageSource) {
        this.messageSource = messageSource;
    }


}